<?php
namespace App\Controller;
use Think\Controller;
require_once 'Aes.php';
class OrgBaseController extends Controller {

    public function test1(){
        // $s = 'daxuan0307啊实打实大谁定阿斯达asd按时！！￥%……&';
        // $a = $this->encryptAES($s);
        // echo "加密：".$a;
        // echo '<pre>';
        // $b = $this->decryptAES($a);
        // echo "解密：".$b;
        $s = 'asdasd啊实打实大十大asdasd';
        $a = $this->publicEncryptRSA($s);
        echo '公钥加密：'.$a.'<pre>';
        $b = $this->privateDecryptRSA($a);
        echo '私钥解密：'.$b;

    }

    //验证安全性
    public function Security($checkToken = true){

        //系统维护中...
        // $this->backToClient(999,'系统维护中...');

        $request = $_POST['request'];

        //解密请求
        $json = $this->decryptAES($request);
        if (empty($json)) {
            $this->backToClient(301,'解密失败，非法数据请求');
        }

        //json转数组
        $json_arr = json_decode($json,true);

        //1.请求时间判断
        if ($json_arr['time'] < time() - 30) {
            $this->backToClient(302,'请求超时');
        }

        //2.验证token
        if($checkToken){
            $condition['midiclub_token'] = $json_arr['token'];
            if(empty(M('midiclub')->where($condition)->find())){
                $this->backToClient(303,'您的账号已经在别处登录，请重新登录');
            }
        }

        //3.验证签名
        if (!($this->checkSign($json_arr))) {
            $this->backToClient(304, '验证签名未通过!');
        }

        //成功返回数组
        return $json_arr;
    }

    // AES加密
    public function encryptAES($data) {
        $aes = new \Aes();
        return $aes->encrypt($data);
    }

    // AES解密
    public function decryptAES($data) {
        $aes = new \Aes();
        return $aes->decrypt($data);
    }

    // 私钥RSA加密
    public function privateEncryptRSA($str) {
        $privateKey = openssl_pkey_get_private(file_get_contents(C('RSA_PRIVATE_KEY')));
        openssl_private_encrypt($str, $encrypted, $privateKey);
        openssl_free_key($privateKey);
        return base64_encode($encrypted);
    }

    // 私钥RSA解密
    public function privateDecryptRSA($str) {
        $privateKey = openssl_pkey_get_private(file_get_contents(C('RSA_PRIVATE_KEY')));
        openssl_private_decrypt(base64_decode($str), $decrypted, $privateKey);
        openssl_free_key($privateKey);
        return $decrypted;
    }

    // 公钥RSA加密
    public function publicEncryptRSA($str) {
        $publicKey = openssl_pkey_get_public(file_get_contents(C('RSA_PUBLIC_KEY')));
        openssl_public_encrypt($str, $encrypted, $publicKey );
        openssl_free_key($publicKey);
        return base64_encode($encrypted);
    }

    // 公钥RSA解密
    public function publicDecryptRSA($str) {
        $publicKey = openssl_pkey_get_public(file_get_contents(C('RSA_PUBLIC_KEY')));
        openssl_public_encrypt(base64_decode($str), $decrypted, $publicKey );
        openssl_free_key($publicKey);
        return $decrypted;
    }

    //验证签名
    public function checkSign($params = array()) {
        ksort($params);
        $paramsStr = '';

        foreach ($params as $key=>$value) {
            if ($key != 'sign') {
                $paramsStr .= $key.'='.$value.'&';
            }
        }

        if ($paramsStr) {
            $paramsStr = substr($paramsStr, 0, -1);
        }

        $sign = $this->privateDecryptRSA($params['sign']);
        return $sign == md5($paramsStr) ? true : false;
    }

    //生成签名
    public function makeSign($params = array()) {
        ksort($params);
        $paramsStr = '';

        foreach ($params as $key=>$value) {
            if ($key != 'sign') {
                $paramsStr .= $key.'='.$value.'&';
            }
        }

        if ($paramsStr) {
            $paramsStr = substr($paramsStr, 0, -1);
        }

        $sign = md5($paramsStr);
        $params['sign'] = $this->publicEncryptRSA($sign);

        $result = $this->encryptAES(json_encode($params));
        echo $result;
    }

    //返回客户端数据
    public function backToClient($status,$msg,$data = array()){
        $result = array();
        $result['status'] = $status;
        $result['msg'] = $msg;
        $result['data'] = $data;
        //数组转json
        $json = json_encode($result);
        //返回数据需要AES加密
        $response_arr['response'] = $this->encryptAES($json);
        echo json_encode($response_arr);
        exit();
    }

    //返回客户端数据（未加密）
    public function backToClient1($status,$msg,$data = array()){
        $result = array();
        $result['status'] = $status;
        $result['msg'] = $msg;
        $result['data'] = $data;
        echo json_encode($result);
        exit();
    }

    public function getUserSig($id){

        if (empty($id)) {
            $this->backToClient(11,'获取UserSig失败');
        }

        Vendor('TLS.Tls');
        //迷笛test（ECkey）
        $pri_key = "MHQCAQEEICU8wjHEEx2V0nVWSN1PlZ6u6IjQaUDq6zxES4o5DesVoAcGBSuBBAAKoUQDQgAE9iEVDp2mqyvxYvakuYcc02rziQanOd1GtJLDWfuXeMELY750Mqr/QjrwGH+ly6XW+cUCKlRhRys8SFi3SpIlKw==";
        //迷笛机构端（ECkey）
        // $pri_key = "MHcCAQEEID6Re83Qi8HXZ/TJu4u9qcFVvHVe4sVlDn/diDWrDqDyoAoGCCqGSM49AwEHoUQDQgAE8NLpiGbNIjkGBZkmNYPYf79ItfDg7jHULHK8YLyQwXXz1OyOIx8BjfhW3zMOiQm9sSEJBa3TVZqDmS0DXnGW6Q==";
        $api = new \TLSSigAPI();

        // 设置在腾讯云申请的appid
        $api->SetAppid(1400031857);

        // 生成usersig需要先设置私钥
        $api->SetPrivateKey($pri_key);

        // 生成usersig
        $sig = $api->genSig($id);

        return $sig;
    }

}